<?php
require_once(__PHY_LIB.'/class/Item.class.php');

class uWorkAlbum extends Item {
/// definition and constructor ///
    function uWorkAlbum($id=0, $field="") {
        Query::Query();
        $this->cfgKeyField("id");
        $this->cfgAllField("id,work_id,rank,title,title_en,time_added,thumb");
        $this->cfgTable("unit_work_album");
        if ("" == $field || "*" == $field) {
            $this->cfgField($this->mAllField);
        }
        else {
            $this->cfgField($field);
        }
        if (0 < $id) {
            $this->cfgWhere($this->mKeyField . "=" . $id);
            $this->load();
        }
        else {
            $this->set($this->mKeyField, $id);
        }
    }

    function invalid() {
        if (!$this->get('title')) {
            return 'title';
        }

        return false;
    }

/// 顺序相关 ///
	function calcNewRank() {
		$sQ = "SELECT MAX(rank) max_rank FROM unit_work_album WHERE work_id='".(int)$this->get('work_id')."'";
		$this->loadQuery($sQ);
		$r = $this->nextRecord(false);
		return (int)$r['max_rank'] + 1;
	}
	function rankTo($nRank) {
		if (!(0 < $this->getID())) { return false; }
		$nRank = max(1, (int)$nRank);
		if ($nRank > $this->get('rank')) { // 增大
			$oList = new uWorkAlbumList();
			$oList->cfgWhere("work_id='".$this->get('work_id')."' AND rank>'".$this->get('rank')."' AND rank<='{$nRank}'");
			$oList->load();
			while ($o = $oList->nextItem()) {
				$o->set('rank', $o->get('rank') - 1); // 中间的统统-1
				$o->update();
			}
		}
		elseif ($nRank < $this->get('rank')) { // 减小
			$oList = new uWorkAlbumList();
			$oList->cfgWhere("work_id='".$this->get('work_id')."' AND rank<'".$this->get('rank')."' AND rank>='{$nRank}'");
			$oList->load();
			while ($o = $oList->nextItem()) {
				$o->set('rank', $o->get('rank') + 1); // 中间的统统+1
				$o->update();
			}
		}
		else { // 相等，没变动
			return true;
		}
		/// 修改自己 ///
		$this->set('rank', $nRank);
		$this->update();
		return true;
	}

/// 缩略图相关 ///
    function calcThumbUrl($nID, $sFile) {
		if (!(0 < $nID)) { $nID = $this->getID(); }
        if (!(0 < $nID)) { return false; }
        if (!$sFile) { return false; }
        $sNumber = str_pad($nID, 9, '0', STR_PAD_LEFT);
		$sDir = "/".substr($sNumber, 0, 3)."/".substr($sNumber, 3, 3)."/".substr($sNumber, 6, 3)."/";
		return "/workalbum{$sDir}{$sFile}";
    }
    function saveThumb($sSrcPath) {
		ini_set('memory_limit', '512M'); // 为了图片处理，临时放开内存限制。
        /// 得到图片信息 ///
        list($nOldW, $nOldH, $nType) = getimagesize($sSrcPath);
        if (IMAGETYPE_GIF == $nType) {
			$hOld = imagecreatefromgif($sSrcPath);
			$sExt = 'gif';
        }
        elseif (IMAGETYPE_JPEG == $nType) {
            $hOld = imagecreatefromjpeg($sSrcPath);
			$sExt = 'jpg';
        }
        elseif (IMAGETYPE_PNG == $nType) {
            $hOld = imagecreatefrompng($sSrcPath);
			$sExt = 'png';
        }
		else { return false; } // 只支持gif/jpg/png
		/// 保存源文件 ///
		if (!($sUrl = $this->calcThumbUrl(null, "source.{$sExt}"))) { return false; }
		mkdir_plus(dirname(__PHY_STO.$sUrl)); // 生成目录
		move_uploaded_file($sSrcPath, __PHY_STO.$sUrl); // 保存
		$sSrcPath = __PHY_STO.$sUrl;
		/// 生成图片 ///
		$rTypes = array(
			'59x59.jpg',
			'585x415.jpg',
		);
		$cnt = 0;
		foreach ($rTypes as $sFile) {
			if (!($sUrl = $this->calcThumbUrl(null, $sFile))) { continue; }
			mkdir_plus(dirname(__PHY_STO.$sUrl)); // 生成目录
			preg_match('/^(\d+)x(\d+)\.(\w+)$/', $sFile, $r);
			list($x, $nNewW, $nNewH, $sExt) = $r;
			$hNew = imagecreatetruecolor($nNewW, $nNewH);
			$cWhite = imagecolorallocate($hNew, 255, 255, 255);
			imagefilledrectangle($hNew, 0, 0, $nNewW, $nNewH, $cWhite); // 画一个白底
			list($fRangeW, $fRangeH) = scale_rectangle(array($nNewW, $nNewH), array($nOldW, $nOldH), 'IN', 'EQUAL'); // 从原始图中算的copy范围
			imagecopyresampled($hNew, $hOld,
				0, 0, round(($nOldW - $fRangeW)/2), round(($nOldH - $fRangeH)/2),
				$nNewW, $nNewH, round($fRangeW), round($fRangeH));
			imagejpeg($hNew, __PHY_STO.$sUrl); // 保存
			imagedestroy($hNew);
			$cnt++;
		}
		imagedestroy($hOld);
		/// 标记已有图片 ///
		if ($cnt == sizeof($rTypes)) {
        	$this->set('thumb', 1);
			return true;
		}
		else { return false; }
	}
} /// end class uWorkAlbum.


class uWorkAlbumList extends ItemList {
    /// definition and constructor ///
    function uWorkAlbumList($tablename=null) {
        ItemList::ItemList();
        $this->cfgClass("uWorkAlbum");
        $this->cfgKeyField("id");
        $this->cfgAllField("id,work_id,rank,title,title_en,time_added,thumb");
        $this->cfgTable(null == $tablename ? "unit_work_album" : $tablename);
    }

} /// end class uWorkAlbumList.


/// related functions ///
function uWorkAlbum_thumb($bHasThumb, $nID, $sFile) {
	if ($bHasThumb) {
		$sUrl = uWorkAlbum::calcThumbUrl($nID, $sFile);
	}
	else { $sUrl = "/workalbum/default/{$sFile}"; }
	return __DIR_STO.$sUrl;
}
function uWorkAlbum_i18n($nID, $sField) {
	static $rCache = array();
	if (!isset($rCache['LangFields'])) {
		$rCache['LangFields'] = '|title';
	}
	if (!isset($rCache[$nID])) {
		$oOne = new uWorkAlbum($nID);
		$rCache[$nID] = $oOne->getData();
	}
	if ('en' == $_SESSION['LANG'] && strpos($rCache['LangFields'], $sField)) {
		$sField .= '_en';
		return $rCache[$nID][$sField];
	}
	else { return $rCache[$nID][$sField]; }
}

?>
